package org.dom4j.tree;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

public class DefaultDocument implements Document {

  Element rootElement;
  
  public Element addElement(String name) {
    if (rootElement != null) {
      rootElement.detach();
    }
    rootElement = new DefaultElement(this, name);
    return rootElement;
  }

  public Element getRootElement() {
    return rootElement;
  }

  public String getXMLEncoding() {
    return "utf8";
  }

  public String asXML() {
    return rootElement.asXML();
  }

  public void add(Element element) {
    if (rootElement != null) {
      rootElement.detach();
    }
    rootElement = element;
    ((DefaultElement)element).setDocument(this);
  }

  public void add(Node element) {
    
  }

  public Node detach() {
    throw new UnsupportedOperationException();
  }

  public List selectNodes(String xpath) {
    // TODO Auto-generated method stub
    // ("/" + ACTION_SEQUENCE + "/" + ACTIONS_NAME
    // support standard traversal
    System.out.println("Document.selectNodes XPATH = " + xpath);
    // This does not support advanced stuff yet
    String paths[] = xpath.split("/");
    int start = 0;
    if (paths.length > 0 && paths[0].equals("")) {
      start = 1;
    }
    if (!paths[start].equals(rootElement.getName())) {
      return new ArrayList();
    }
    start++;
    List allElements = new ArrayList();
    allElements.add(rootElement);

    for (int i = start; i < paths.length; i++) {
      List foundElements = new ArrayList();
      for (int j = 0; j < allElements.size(); j++) {
        Element currElement = (Element)allElements.get(j);
        foundElements.addAll(currElement.elements(paths[i]));
      }
      allElements = foundElements;
    }
    return allElements;
  }

  public Node selectSingleNode(String xpath) {
    List list = selectNodes(xpath);
    if (list.size() > 0) {
      return (Node)list.get(0);
    }
    return null;
  }

  public String getText() {
    throw new UnsupportedOperationException();
  }

  public void setText(String text) {
    throw new UnsupportedOperationException();
  }

  public String getName() {
    throw new UnsupportedOperationException();
  }

  public Element getParent() {
    throw new UnsupportedOperationException();
  }
  
  public void setParent(Element parent) {
    throw new UnsupportedOperationException();
  }

}
